import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.*
import com.lesliefang.SignUtil
import java.io.File

@Composable
@Preview
fun App() {
    var folderPath by remember { mutableStateOf("") }
    var encryptText by remember { mutableStateOf("") }
    var decryptText by remember { mutableStateOf("") }
    var logText by remember { mutableStateOf("") } // 使用单个字符串存储日志，而不是列表

    // 自定义主题颜色
    val customColors = lightColors(
        background = androidx.compose.ui.graphics.Color.White,
        surface = androidx.compose.ui.graphics.Color.White,
        onSurface = androidx.compose.ui.graphics.Color.Black
    )

    MaterialTheme(colors = customColors) {
        Column(modifier = Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
            // 第一行：选择文件夹
            Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
                OutlinedTextField(
                    value = folderPath,
                    onValueChange = { folderPath = it },
                    modifier = Modifier.weight(1f),
                    label = { Text("选择一个文件夹，如果里面没有material会自动生成一个，有material就会用里面的material加解密") },
                    readOnly = true,
                    colors = TextFieldDefaults.outlinedTextFieldColors(
                        backgroundColor = androidx.compose.ui.graphics.Color.White,
                        textColor = androidx.compose.ui.graphics.Color.Black,
                        focusedBorderColor = MaterialTheme.colors.primary,
                        unfocusedBorderColor = androidx.compose.ui.graphics.Color.Gray
                    )
                )
                Spacer(modifier = Modifier.width(8.dp))
                Button(onClick = {
                    // 使用JFileChooser代替FileDialog，JFileChooser在所有平台上都支持选择文件夹
                    val fileChooser = javax.swing.JFileChooser().apply {
                        fileSelectionMode = javax.swing.JFileChooser.DIRECTORIES_ONLY
                        dialogTitle = "选择文件夹"
                        approveButtonText = "选择"
                        approveButtonToolTipText = "选择此文件夹"
                    }

                    val result = fileChooser.showOpenDialog(null)

                    if (result == javax.swing.JFileChooser.APPROVE_OPTION) {
                        val selectedFile = fileChooser.selectedFile
                        folderPath = selectedFile.absolutePath
                    }
                }) {
                    Text("选择")
                }
            }

            // 第二行：加密
            Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
                OutlinedTextField(
                    value = encryptText,
                    onValueChange = { encryptText = it },
                    modifier = Modifier.weight(1f),
                    label = { Text("输入要加密的密码") },
                    colors = TextFieldDefaults.outlinedTextFieldColors(
                        backgroundColor = androidx.compose.ui.graphics.Color.White,
                        textColor = androidx.compose.ui.graphics.Color.Black,
                        focusedBorderColor = MaterialTheme.colors.primary,
                        unfocusedBorderColor = androidx.compose.ui.graphics.Color.Gray
                    )
                )
                Spacer(modifier = Modifier.width(8.dp))
                Button(onClick = {
                    // 加密逻辑
                    val file = File(folderPath)
                    if (file.exists() && encryptText.isNotEmpty()) {
                        try {
                            // 调用 SignUtil 的静态方法进行加密
                            val encryptedResult = SignUtil.getEncryptPassword(folderPath, encryptText.trim())
                            logText += "加密成功: $encryptedResult\n"
                        } catch (e: Exception) {
                            logText += "加密失败: ${e.message}\n"
                        }
                    } else {
                        logText += "请先选择文件夹并输入要加密的密码\n"
                    }
                }) {
                    Text("加密")
                }
            }

            // 第三行：解密
            Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
                OutlinedTextField(
                    value = decryptText,
                    onValueChange = { decryptText = it },
                    modifier = Modifier.weight(1f),
                    label = { Text("输入要解密的密码") },
                    colors = TextFieldDefaults.outlinedTextFieldColors(
                        backgroundColor = androidx.compose.ui.graphics.Color.White,
                        textColor = androidx.compose.ui.graphics.Color.Black,
                        focusedBorderColor = MaterialTheme.colors.primary,
                        unfocusedBorderColor = androidx.compose.ui.graphics.Color.Gray
                    )
                )
                Spacer(modifier = Modifier.width(8.dp))
                Button(onClick = {
                    // 解密逻辑
                    val file = File(folderPath)
                    if (file.exists() && decryptText.isNotEmpty()) {
                        try {
                            // 调用 SignUtil 的静态方法进行解密
                            val decryptedResult = SignUtil.getDecryptPassword(folderPath, decryptText.trim())
                            logText += "解密成功: $decryptedResult\n"
                        } catch (e: Exception) {
                            logText += "解密失败: ${e.message}\n"
                        }
                    } else {
                        logText += "请先选择文件夹并输入要解密的密码\n"
                    }
                }) {
                    Text("解密")
                }
            }

            // 日志区域
            Card(
                modifier = Modifier.fillMaxWidth().weight(1f),
                backgroundColor = androidx.compose.ui.graphics.Color.White,
                elevation = 2.dp  // 轻微的阴影效果
            ) {
                Box(modifier = Modifier.fillMaxSize().padding(8.dp)) {
                    // 使用TextField替代LazyColumn，更简单地实现日志追加
                    TextField(
                        value = logText,
                        onValueChange = { },  // 只读模式
                        modifier = Modifier.fillMaxSize(),
                        readOnly = true,      // 设置为只读
                        maxLines = Int.MAX_VALUE,  // 允许多行显示
                        colors = TextFieldDefaults.textFieldColors(
                            backgroundColor = androidx.compose.ui.graphics.Color.White,  // 设置背景为白色
                            textColor = androidx.compose.ui.graphics.Color.Black,      // 设置文本颜色为黑色
                            focusedIndicatorColor = androidx.compose.ui.graphics.Color.Transparent,  // 去掉聚焦时的下划线
                            unfocusedIndicatorColor = androidx.compose.ui.graphics.Color.Transparent,  // 去掉非聚焦时的下划线
                            cursorColor = androidx.compose.ui.graphics.Color.Black     // 设置光标颜色为黑色
                        )
                    )

                    Button(
                        onClick = { logText = "" },  // 清空日志文本
                        modifier = Modifier.align(Alignment.BottomEnd).padding(8.dp)
                    ) {
                        Text("清除日志")
                    }
                }
            }
        }
    }
}

fun main() = application {
    // 添加一个状态变量来控制关于窗口的显示
    var showAboutDialog by remember { mutableStateOf(false) }

    Window(
        onCloseRequest = ::exitApplication,
        title = "鸿蒙签名密码加解密工具",
        onPreviewKeyEvent = { false }
    ) {
        // 设置菜单栏
        MenuBar {
            Menu("帮助") {
                Item("关于", onClick = { showAboutDialog = true })
            }
        }

        // 主应用界面
        App()

        // 关于对话框
        if (showAboutDialog) {
            // 使用 Dialog 替代 AlertDialog 以避免实验性 API 警告
            Dialog(
                onCloseRequest = { showAboutDialog = false },
                title = "关于",
                state = rememberDialogState(width = 300.dp, height = 230.dp)
            ) {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    Column(modifier = Modifier.padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) {
                        Text("鸿蒙签名密码加解密工具", style = MaterialTheme.typography.h6)
                        Spacer(Modifier.height(8.dp))
                        Text("版本: 1.0.0")
                        Spacer(Modifier.height(8.dp))
                        Text("微信公众号@KotlinFang 头条@青岛房老师 知乎@青岛房老师 ©2025 版权所有")
                        Spacer(Modifier.height(16.dp))
                        Button(onClick = { showAboutDialog = false }) {
                            Text("确定")
                        }
                    }
                }
            }
        }
    }
}
